package forum.service;

import java.sql.ResultSet;

import forum.DBConnectie;
import forum.Filter;
import forum.Variable;
import forum.wrapper.WrapRequest;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA. User: Ivan Date: 2010-7-8 Time: 15:31:55
 */
public class Forum {
	DBConnectie db = new DBConnectie(Variable.getDb(), Variable.getDbLogin(),
			Variable.getDbPassword());

	public String add(WrapRequest request) throws Exception {

		String title = request.getParameter("title");
		if (title.equals("")) {
			title = "No title";
		} else {
			title = Filter.filterAll(title);
		}

		String forum_info = request.getParameter("forum_info");
		forum_info = Filter.filterAll(forum_info);

		db.connect();

		ResultSet rs2 = db
				.selectQuery("SELECT MAX(forum_id) forum_id FROM forum_forums");

		String lastforum_id = null;
		while (rs2.next()) {
			lastforum_id = rs2.getString("forum_id");

			if (lastforum_id == null) {
				lastforum_id = "-1";
			}
		}

		String forum_id = Integer.toString(Integer.parseInt(lastforum_id) + 1);

		db.query("INSERT INTO forum_forums(forum_id,title,forum_info) "
				+ "VALUES(\"" + forum_id + "\",\"" + title + "\",\""
				+ forum_info + "\")");

		db.close();

		return "index.jsp";
	}

	public String delete(WrapRequest request) throws Exception {

		HttpSession session = request.getSession(true);
		String sessionType = (String) session.getAttribute("type");

		String forum_id = request.getParameter("forum_id");

		if (sessionType.equals("Admin")) {

			db.connect();

			db.query("DELETE FROM forum_message WHERE forum_id=\"" + forum_id
					+ "\"");
			db.query("DELETE FROM forum_forums WHERE forum_id=\"" + forum_id
					+ "\"");

			db.close();
		}

		return "index.jsp";
	}
	

}
